package com.archermind.empsys.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {

	
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	private static DataSource ds;
	
	static{
		ds = new ComboPooledDataSource();
	}
		
	public static DataSource getDataSource(){
		return ds;
	}
	
	
	public static Connection getConnection(){
		try{
			Connection conn = tl.get();
			if(conn==null){
				conn = ds.getConnection();
				conn.setAutoCommit(false);
				tl.set(conn);
			}
			return conn;
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
	public static void startTransaction(){
		try {
			Connection conn = getConnection();
			conn.setAutoCommit(false);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void commit(){
		try {
			Connection conn = tl.get();
			if(conn!=null){
				conn.commit();
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void rollback(){
		try {
			Connection conn = tl.get();
			if(conn!=null){
				conn.rollback();
				conn.commit();
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void closeConn(){
		try {
			Connection conn = tl.get();
			try{
				if(conn!=null){
					conn.close();
				}
			}finally{
				tl.remove();
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
